package com.david.trade.api.tcp;

import com.david.trade.api.event.TcpEventSource;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * @author janti
 * @date 2018/5/6 22:59
 */
@Component
@Slf4j
public class ClientHandler extends SimpleChannelInboundHandler<String>{
    @Override
    public void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {

        String msgId = msg.split("#")[0];
        log.info("客户端收到消息: {}, msgId: {}", msg, msgId);
        TcpEventSource tcpEventSource = NettyTcpClient.tcpEventSourceMap.get(msgId);
        if (tcpEventSource != null) {
            tcpEventSource.newEvent(new TcpEventSource.TcpEvent(new Date(), msg.split("#")[1], "1"));
            tcpEventSource.eventStopped();
        }

    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        cause.printStackTrace();
        ctx.close();
    }
}
